/**
 * 人脸识别API代理服务
 * 通过后端代理解决CORS问题
 */

// 人脸质量检测阈值配置
const QUALITY_THRESHOLDS = {
  // 遮挡阈值
  occlusion: {
    left_eye: 0.6,      // 左眼被遮挡的阈值
    right_eye: 0.6,     // 右眼被遮挡的阈值
    nose: 0.7,          // 鼻子被遮挡的阈值
    mouth: 0.7,         // 嘴巴被遮挡的阈值
    left_cheek: 0.8,    // 左脸颊被遮挡的阈值
    right_cheek: 0.8,   // 右脸颊被遮挡的阈值
    chin_contour: 0.6   // 下巴被遮挡阈值
  },
  blur: 0.7,            // 模糊度阈值，小于0.7
  illumination: 40,     // 光照阈值，大于40
  angle: 20,            // 姿态角度阈值，小于20度
  minFaceSize: 100      // 最小人脸尺寸，100*100像素
}

/**
 * 人脸质量检测
 */
function checkFaceQuality(quality: any): { isValid: boolean; message: string } {
  const { occlusion, blur, illumination, completeness } = quality

  // 检查遮挡
  if (occlusion) {
    const occlusionThresholds = QUALITY_THRESHOLDS.occlusion
    for (const [key, threshold] of Object.entries(occlusionThresholds)) {
      if (occlusion[key] > threshold) {
        return {
          isValid: false,
          message: `${key === 'left_eye' ? '左眼' : key === 'right_eye' ? '右眼' : key === 'nose' ? '鼻子' : key === 'mouth' ? '嘴巴' : key === 'left_cheek' ? '左脸颊' : key === 'right_cheek' ? '右脸颊' : '下巴'}被遮挡，请调整角度`
        }
      }
    }
  }

  // 检查模糊度
  if (blur >= QUALITY_THRESHOLDS.blur) {
    return {
      isValid: false,
      message: '图片模糊，请保持稳定并重新拍摄'
    }
  }

  // 检查光照
  if (illumination < QUALITY_THRESHOLDS.illumination) {
    return {
      isValid: false,
      message: '光线不足，请调整光线环境'
    }
  }

  // 检查人脸完整度
  if (completeness !== 1) {
    return {
      isValid: false,
      message: '人脸不完整，请确保人脸完全在画面内'
    }
  }

  return {
    isValid: true,
    message: '人脸质量检测通过'
  }
}

/**
 * 将图片转换为Base64格式
 */
function imageToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      // 移除data:image/jpeg;base64,前缀
      const base64 = result.split(',')[1]
      resolve(base64)
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 人脸检测和质量评估（通过后端代理）
 */
export async function detectFace(imageBase64: string): Promise<{
  success: boolean
  data?: any
  message: string
}> {
  try {
    // 调用后端代理API
    const response = await fetch('/api/face/detect', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        face_field: 'quality,angle,face_shape,landmark'
      })
    })

    const data = await response.json()
    
    if (!response.ok) {
      return {
        success: false,
        message: data.message || '人脸检测失败'
      }
    }

    if (data.face_num === 0) {
      return {
        success: false,
        message: '未检测到人脸，请确保人脸在画面中'
      }
    }

    if (data.face_num > 1) {
      return {
        success: false,
        message: '检测到多张人脸，请确保画面中只有一张人脸'
      }
    }

    const face = data.face_list[0]
    
    // 检查人脸大小
    const { width, height } = face.location
    if (width < QUALITY_THRESHOLDS.minFaceSize || height < QUALITY_THRESHOLDS.minFaceSize) {
      return {
        success: false,
        message: '人脸太小，请靠近摄像头'
      }
    }

    // 检查姿态角度
    const { yaw, pitch, roll } = face.angle
    if (Math.abs(yaw) > QUALITY_THRESHOLDS.angle || 
        Math.abs(pitch) > QUALITY_THRESHOLDS.angle || 
        Math.abs(roll) > QUALITY_THRESHOLDS.angle) {
      return {
        success: false,
        message: '人脸角度过大，请正面面对摄像头'
      }
    }

    // 检查人脸质量
    const qualityCheck = checkFaceQuality(face.quality)
    if (!qualityCheck.isValid) {
      return {
        success: false,
        message: qualityCheck.message
      }
    }

    return {
      success: true,
      data: face,
      message: '人脸检测成功'
    }
  } catch (error) {
    console.error('人脸检测错误:', error)
    return {
      success: false,
      message: '人脸检测失败，请检查网络连接'
    }
  }
}

/**
 * 人脸特征提取（用于注册）
 */
export async function extractFaceFeature(imageBase64: string): Promise<{
  success: boolean
  data?: any
  message: string
}> {
  try {
    // 调用后端代理API
    const response = await fetch('/api/face/detect', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        face_field: 'feature,quality,angle,face_shape,landmark'
      })
    })

    const data = await response.json()
    
    if (!response.ok) {
      return {
        success: false,
        message: data.message || '特征提取失败'
      }
    }

    if (data.face_num === 0) {
      return {
        success: false,
        message: '未检测到人脸，请确保人脸在画面中'
      }
    }

    const face = data.face_list[0]
    
    // 检查人脸质量
    const qualityCheck = checkFaceQuality(face.quality)
    if (!qualityCheck.isValid) {
      return {
        success: false,
        message: qualityCheck.message
      }
    }

    return {
      success: true,
      data: {
        face_token: face.face_token,
        feature: face.feature,
        quality: face.quality,
        location: face.location
      },
      message: '特征提取成功'
    }
  } catch (error) {
    console.error('特征提取错误:', error)
    return {
      success: false,
      message: '特征提取失败，请检查网络连接'
    }
  }
}

/**
 * 人脸比对
 */
export async function compareFaces(imageBase64: string, targetFaceToken: string): Promise<{
  success: boolean
  data?: any
  message: string
}> {
  try {
    // 调用后端代理API
    const response = await fetch('/api/face/match', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify([
        {
          image: imageBase64,
          image_type: 'BASE64',
          face_field: 'feature'
        },
        {
          image: targetFaceToken,
          image_type: 'FACE_TOKEN'
        }
      ])
    })

    const data = await response.json()
    
    if (!response.ok) {
      return {
        success: false,
        message: data.message || '人脸比对失败'
      }
    }

    const score = data.result?.score || 0
    const threshold = 80 // 相似度阈值，可根据需要调整

    return {
      success: score >= threshold,
      data: {
        score,
        threshold
      },
      message: score >= threshold ? '人脸比对成功' : '人脸不匹配'
    }
  } catch (error) {
    console.error('人脸比对错误:', error)
    return {
      success: false,
      message: '人脸比对失败，请检查网络连接'
    }
  }
}

/**
 * 将File对象转换为Base64
 */
export async function fileToBase64(file: File): Promise<string> {
  return imageToBase64(file)
}

export { QUALITY_THRESHOLDS }
